﻿package com.neriksworkshop.colourLoversDemos.colourLoversBrowser 
{
	import com.neriksworkshop.lib.colourLovers.requests.params.Format;
	import flash.display.Sprite;
	import flash.events.Event;	
	
	import com.neriksworkshop.lib.colourLovers.events.RequestEvent;
	import com.neriksworkshop.lib.colourLovers.RequestManager;
	import com.neriksworkshop.lib.colourLovers.requests.IRequest;
	import com.neriksworkshop.lib.colourLovers.requests.ColorRequest;
	import com.neriksworkshop.lib.colourLovers.requests.PaletteRequest;
	import com.neriksworkshop.lib.colourLovers.requests.PatternRequest;
	
	
	/**
	 * ...
	 * @author Erik
	 */
	public class MainController extends Sprite
	{
		private var rm:RequestManager;
		
		public function MainController() 
		{
			
			rm = RequestManager.getInstance();
						
			ui.addEventListener("submit", onSubmit);
			
		}
		
		private function onSubmit(e:Event):void 
		{
			var dataObj:Object = ui.currentDataObj;
			
			var req:IRequest;
			
			//req.format = Format.FMT_JSON;
			
			switch (dataObj.type)
			{
				case "Color" :   req = new ColorRequest(); break;
				case "Palette" :   req = new PaletteRequest(); break;
				case "Pattern" :   req = new PatternRequest(); break;
				
			}
			
			
			for (var name:String in ui.currentDataObj) 
			{
				//trace(name, ui.currentDataObj[name]);
				if (name == "type") 			continue;
				else if (name == "keywords") 	req[name] = (ui.currentDataObj.keywords).split(" ");
				else 							req[name] = ui.currentDataObj[name];
			}
			
			req.addEventListener(RequestEvent.RESULTS, onRequestComplete);
			req.addEventListener(RequestEvent.NO_RESULTS, onRequestEmpty);
			rm.request(req as IRequest);

		}
		
		private function onRequestEmpty(e:RequestEvent):void 
		{
			trace("no reults")
		}
		
		private function onRequestComplete(e:RequestEvent):void 
		{
			var req:IRequest = e.request;
			//var dataObjects:Array;
			//var dataText:String = String(req.xmlData);
			//var type:Class;
			
			/*
			if (req is ColorRequest) 	
			{
				type = ColorRequest;
				dataObjects = (req as type).colors;
			}
			if (req is PaletteRequest) 
			{
				type = PaletteRequest;
				dataObjects = (req as type).palettes;			
			}*/
			
			ui.showResults(req);
		}
		
	}
	
}